package com.tianci.appstore.ui.mainpage;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.coocaa.x.app.framework.app.LiteAppApplication;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.framework.utils.PMUtils.PackageMoveLocation;
import com.coocaa.x.service.XServiceManager;
import com.tianci.appstore.AppListActivity;
import com.tianci.appstore.AppListActivity.ListActivityType;
import com.tianci.appstore.MoreManageActivity;
import com.tianci.appstore.R;
import com.tianci.appstore.controller.manager.MoveManagerController;
import com.tianci.appstore.ui.SkinManager;
import com.tianci.appstore.ui.about.AboutUsActivity;
import com.tianci.appstore.ui.data.SkyAppBaseData;
import com.tianci.appstore.ui.data.SkyListAppData.ListType;
import com.tianci.appstore.ui.data.SkyManageBlockData;
import com.tianci.appstore.ui.data.SkyManageBlockData.ManagerBlock;
import com.tianci.appstore.ui.dialog.ConfirmProcessDialog;
import com.tianci.appstore.ui.dialog.MoveSelectDialog;
import com.tianci.appstore.ui.util.UICommon;
import com.tianci.appstore.ui.widget.AlwaysMarqueeTextView;
import com.tianci.appstore.ui.widget.OnButtonClickListener;
import com.tianci.appstore.ui.widget.SkyBaseItemView;
import com.tianci.appstore.ui.widget.TipToast;
import com.tianci.appstore.utils.SkyConstants;

import java.util.HashMap;
import java.util.Map;

public class ManageBlock extends SkyBaseItemView implements OnButtonClickListener {
    private ImageView iconImage;
    private static int iconWidth = SkyConstants.Div(172);
    private static int titleSize = SkyConstants.Dpi(35);
    private TextView mRedPoint = null;
    private MoveSelectDialog mDialog = null;
    private ConfirmProcessDialog mProcessDialog = null;
    private long mTempSize = 0;

    public ManageBlock(Context context) {
        super(context);
    }

    @Override
    protected void createView() {
        // TODO Auto-generated method stub
        iconImage = new ImageView(mContext);
        iconImage.setScaleType(ScaleType.CENTER_CROP);
        LayoutParams iconParams = new LayoutParams(iconWidth, iconWidth, Gravity.CENTER_VERTICAL);
        iconParams.leftMargin = SkyConstants.shadowWidth + SkyConstants.Div(35);
        this.addView(iconImage, iconParams);

        titleText = new AlwaysMarqueeTextView(mContext);
        titleText.setGravity(Gravity.CENTER);
        titleText.setSelected(false);
        titleText.setTextSize(titleSize);
        titleText.setPadding(SkyConstants.Div(20), 0, SkyConstants.Div(20), 0);
        SkinManager.setTextColor(titleText, R.color.titleColor);
        LayoutParams titleParams = new LayoutParams(SkyConstants.Div(240),
                LayoutParams.WRAP_CONTENT, Gravity.CENTER_VERTICAL);
        titleParams.leftMargin = SkyConstants.Div(240);
        this.addView(titleText, titleParams);
    }

    public void addRedPoint(int num) {
        if (mRedPoint == null) {
            mRedPoint = new TextView(mContext);
            mRedPoint.setGravity(Gravity.CENTER);
            mRedPoint.setTextColor(Color.WHITE);
            SkinManager.setBackground(mRedPoint, R.drawable.pic_redpoint);
            mRedPoint.setTextSize(SkyConstants.Dpi(32));
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(SkyConstants.Div(56),
                    SkyConstants.Div(58));
            params.setMargins(SkyConstants.Div(185), SkyConstants.Div(20), 0, 0);
            addView(mRedPoint, params);
        }
        mRedPoint.setText(String.valueOf(num));
        mRedPoint.setVisibility(View.VISIBLE);
    }

    private void hiddinRedPoint() {
        if (mRedPoint != null) {
            mRedPoint.setVisibility(View.GONE);
        }
    }

    @Override
    public void update(SkyAppBaseData data) {
        // TODO Auto-generated method stub
        this.data = data;
        if (data.getTitle() != null)
            titleText.setText(data.getTitle());
        LogUtils.d("count is " + ((SkyManageBlockData) data).getUpdateCount());
        if (((SkyManageBlockData) data).getUpdateCount() != 0) {
            addRedPoint(((SkyManageBlockData) data).getUpdateCount());
        } else {
            hiddinRedPoint();
        }
        if (data.getIconUrl() != null) {
            Integer id = SkyConstants.getIconId(data.getIconUrl());
            iconImage.setImageResource(id);
        }
    }

    @Override
    protected void refreshImage(String url, Bitmap result) {
    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        ManagerBlock blockType = ManagerBlock.valueOf(this.data.getId());
        Intent intent = new Intent();
        if (blockType == ManagerBlock.ABOUT) {
            intent.setClass(mContext, AboutUsActivity.class);
            mContext.startActivity(intent);
        } else if (blockType == ManagerBlock.SPEED) {
            try {
                XServiceManager.getLitePMService().speedUp(5000);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        } else if (blockType == ManagerBlock.MORE) {
            intent.setClass(mContext, MoreManageActivity.class);
            mContext.startActivity(intent);
        } else if (blockType == ManagerBlock.REMOTE_INSTALL){
            final String ACTION = "com.coocaa.x.webservice.activity";
            intent.setAction(ACTION);
            mContext.startActivity(intent);
        }  else {
            AppListActivity.type = ListActivityType.DOWNLOAD_LIST;
            intent.setClass(mContext, AppListActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ListType listType = ListType.DOWNLOAD_LIST;
            switch (blockType) {
                case CLEAN:
                    AppListActivity.type = ListActivityType.CLEAR_LIST;
                    listType = ListType.CLEAR_CACHE_LIST;
                    break;
                case DELETE:
                    AppListActivity.type = ListActivityType.UNINSTALL_LIST;
                    listType = ListType.UNINSTALL_APP_LIST;
                    break;
                case DOWNLOAD:
                    if (!LiteAppApplication.checkNetworkConnection(TipToast.showNetIsNotConnectedToastRunnable))
                        return;
                    AppListActivity.type = ListActivityType.DOWNLOAD_LIST;
                    listType = ListType.DOWNLOAD_LIST;
                    break;
                case MOVE:
                    listType = ListType.MOVE_APP_LIST;
                    if (MoveManagerController.getInstance(mContext).isSDCardAvaiable()) {
                        mDialog = new MoveSelectDialog(mContext);
                        mDialog.setButtonClickListener(this);
                        mDialog.show();
                        MoveManagerController controller = MoveManagerController
                                .getInstance(mContext);
                        mDialog.updateExternalApp(
                                controller.getInstallAppSize(PackageMoveLocation.EXTERNAL_MEDIA),
                                UICommon.sizeToString(controller.getSDcardAvailableSpace()));
                        mDialog.updateNativeApp(
                                controller.getInstallAppSize(PackageMoveLocation.INTERNAL_MEMORY),
                                UICommon.sizeToString(controller.getAvailableInternalMemorySize()));
                    } else {
                        TipToast.getInstance(mContext).showTipToast(
                                mContext.getString(R.string.please_plug_sdcard));
                    }
                    return;
                case UPDATE:
                    if (!LiteAppApplication.checkNetworkConnection(TipToast.showNetIsNotConnectedToastRunnable))
                        return;
                    AppListActivity.type = ListActivityType.UPDATE_LIST;
                    listType = ListType.UPGRADE_APP_LIST;
                    break;
                case SCAN:
                    AppListActivity.type = ListActivityType.APK_SCAN;
                    listType = ListType.APK_SCAN_LIST;
                    break;
                case AUTOSTART:
                    listType = ListType.LAUNCH_ON_BOOT_LIST;
                    break;
//                case REMOTE_INSTALL:
//                    break;
            }
            intent.putExtra("listType", listType.toString());
            mContext.startActivity(intent);
            // hiddinRedPoint();
        }
        Map<String,String> params = new HashMap<String, String>();
        params.put("entry_name",data.getTitle());
        LogUtils.submit(LogUtils.PRODUCTID_APPSTORE,"as2_main_entry_onclick",params);
        super.onClick(arg0);
    }

    private static final int MSG_CLEAN_SUCCESS = 0;
    private static final int MSG_CLEAN_DISMISS = 1;
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_CLEAN_DISMISS:
                    mProcessDialog.dismiss();
                    break;
                case MSG_CLEAN_SUCCESS:
                    long temp = mTempSize / 1024;
                    if (temp == 0) {
                        mProcessDialog.enterResultState("系统已在最优状态");
                    } else {
                        mProcessDialog.enterResultState("内存清理完毕,共释放" + Math.abs(temp) + "MB内存");
                    }
                    break;
                default:
                    break;
            }
        }

        ;
    };

    @Override
    public void onClick(int index) {
        switch (index) {
            case 0:
                if (MoveManagerController.getInstance(mContext).getInstallAppSize(
                        PackageMoveLocation.EXTERNAL_MEDIA) > 0) {
                    if (MoveManagerController.getInstance(mContext)
                            .getAvailableInternalMemorySize() > 100) {
                        startActivityByLocation(PackageMoveLocation.EXTERNAL_MEDIA);
                    } else {
                        TipToast.getInstance(mContext).showTipToast(
                                mContext.getString(R.string.no_internal_free_size));
                    }
                } else {
                    TipToast.getInstance(mContext).showTipToast(
                            mContext.getString(R.string.no_external_apps_to_move));
                }
                break;
            case 1:
                if (MoveManagerController.getInstance(mContext).getInstallAppSize(
                        PackageMoveLocation.INTERNAL_MEMORY) > 0) {
                    if (MoveManagerController.getInstance(mContext).getSDcardAvailableSpace() > 100) {
                        startActivityByLocation(PackageMoveLocation.INTERNAL_MEMORY);
                    } else {
                        TipToast.getInstance(mContext).showTipToast(
                                mContext.getString(R.string.no_external_free_size));
                    }
                } else {
                    TipToast.getInstance(mContext).showTipToast(
                            mContext.getString(R.string.no_internal_apps_to_move));
                }
                break;
            default:
                break;
        }
        if (mDialog != null) {
            mDialog.dismiss();
        }
    }

    public void startActivityByLocation(PackageMoveLocation loaction) {
        Intent intent = new Intent();
        AppListActivity.type = ListActivityType.MOVE_LIST;
        intent.setClass(mContext, AppListActivity.class);
        intent.putExtra("listType", ListType.MOVE_APP_LIST.toString());
        intent.putExtra("location", loaction);
        mContext.startActivity(intent);
    }

    @Override
    public void destory() {
        // TODO Auto-generated method stub

    }
}
